//
//  UserAccessInfo.swift
//  微博框架
//
//  Created by ming on 16/10/11.
//  Copyright © 2016年 ming. All rights reserved.
//

import UIKit
import SVProgressHUD

//账户模型数组:用来保存用户的信息，token，和过期时间
class UserAccessInfo: NSObject {
 
    
    let pathName:String = ("accessToken.json" as NSString).cz_appendDocumentDir()
    //从写构造函数
    override init() {
        super.init()
       //
        //从磁盘中读取出数据
        guard let data = NSData(contentsOfFile: pathName),
         let json = try? JSONSerialization.jsonObject(with: data as Data, options: []) else{
            return
        }
        
        //把json读取到模型数据中
       yy_modelSet(with: json as! [String : AnyObject])
        //token过期处理
        let nowDate = Date()
        
       let results = expiresDate?.compare(nowDate)
        if results != .orderedDescending {
            //tongken过期通知控制器登录
            //SVProgressHUD.showInfo(withStatus: "会话超时请重新登录")
            //通知控制器登录,清空账户
            access_token = nil
            expiresDate = nil
            //删除文件
         try? FileManager.default.removeItem(atPath: pathName)
            
            
            
        }
      //token正常
        
    }
    
    //用户授权的唯一票据
    var  access_token:String? 
//    access_token的生命周期，单位是秒数
    var  expires_in:TimeInterval = 0 {
        didSet{
            //把过期事件计算出来
            expiresDate = Date(timeIntervalSinceNow: expires_in)
            
        }
        
    }
//    授权用户的UID
    var uid:String?
   //过期时间
    var expiresDate:Date?
    
    override var description: String{
        
        return yy_modelDescription()
    }
}

extension UserAccessInfo{
    //把模型数据保存到json
    func accessSaveToken(){
        

        //获取保存文件的路径
       
  
        //写入到磁盘
        var dict = self.yy_modelToJSONObject() as? [String:AnyObject] ?? [:]
          //expires_in不需要保存所以先删除
        dict.removeValue(forKey:"expires_in")
        //转json格式保存
        guard let data = try? JSONSerialization.data(withJSONObject: dict, options: [.prettyPrinted]) as NSData else{
            
            
            return
        }
        //写到磁盘
        data.write(toFile: pathName, atomically: true)
       
        
    }
    
    
}
